# -*- coding:utf-8 -*-

import pika
import config
import traceback

def send_to_queue(proj, para_dict, durable=False):
    """
    信息保存到消息队列
    :param proj:消息队列交接机的配置key
    :param para_dict:数据dict
    :param durable:用来设置exchange是坚固还是非坚固
    :return:
    """
    connection = None
    mq_info = getattr(config, proj)
    try:
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(mq_info['serverip']))
        channel = connection.channel()
        exchange_name = mq_info['exchange_name']
        # 定义交换机，设置类型为direct
        channel.exchange_declare(exchange=exchange_name, type='direct', durable=durable)
        routingkey = mq_info['routing_key']
        channel.basic_publish(exchange=exchange_name,
                              routing_key=routingkey,
                              body=str(para_dict))
    except Exception, ex:
        print traceback.format_exc()
    finally:
        if connection and not connection.is_closed:
            connection.close()